package com.wbao.dianniu.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.listener.IAuthCodeListener;
import com.wbao.dianniu.listener.IForgetPassListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.manager.ForgetPassManager;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.R;


/**
 * 忘记密码&修改密码
 *
 * @author yejianjun
 */
public class ForgetActivity extends BaseActivity implements OnClickListener, IForgetPassListener, IAuthCodeListener {

    //	private ImageButton backBtn;
//	private TextView titleTV;
    private Button completedBtn;
    private EditText mobileEditText, authCodeEditText, passwordEditText;
    private TextView authCodeTV;
    private ForgetPassManager manager;
    /**
     * 1：修改密码  0：忘记密码
     */
    private int type = 0;
    private int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_forget_password);
        initView();
        initData();
        manager = new ForgetPassManager(this);
        manager.addListener(this);
        manager.addAuthListener(this);
    }

    private void initData() {
        Intent intent = getIntent();
        type = intent.getIntExtra(Const.BUNDLE_DATA, 0);
        if (1 == type) {
            setTitleName(R.string.modify_password_title);
            GlobalUserData userData = new GlobalUserData();
            mobileEditText.setText(userData.getMobile());
            mobileEditText.setFocusable(false);
            mobileEditText.setClickable(false);
        } else if (0 == type) {
            setTitleName(R.string.forget_password_title);
        }
    }

    private void initView() {
        // TODO Auto-generated method stub
        completedBtn = findViewById(R.id.forget_ok);
        mobileEditText = findViewById(R.id.forget_mobile);
        authCodeEditText = findViewById(R.id.forget_auth_code);
        passwordEditText = findViewById(R.id.forget_password);
//		authPasswordEditText = (EditText) findViewById(R.id.forget_auth_password);
        authCodeTV = findViewById(R.id.authCode_tv);
        setBaseBackgroundColor(getResources().getColor(R.color.white));
        completedBtn.setOnClickListener(noDoubleClickListener);
        authCodeTV.setOnClickListener(noDoubleClickListener);
        passwordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());

    }

    CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            authCodeTV.setText(millisUntilFinished / 1000 + getResources().getString(R.string.auth_code_get_desc));
        }

        @Override
        public void onFinish() {
            authCodeTV.setEnabled(true);
            authCodeTV.setText(getResources().getString(R.string.register_get_auth_password));
        }
    };


    /*@Override
    public void onClick(View v) {
        super.onClick(v);
    }*/


    NoDoubleClickListener noDoubleClickListener = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            String mobile = mobileEditText.getText().toString().trim();
            String code = authCodeEditText.getText().toString().trim();
            String password = passwordEditText.getText().toString().trim();
            switch (v.getId()) {
                case R.id.forget_ok:
                    if (authMobile(mobile) && authPsd(password, code)) {
                        if (count > 5) {
                            Notification.toast(ForgetActivity.this, getResources().getString(R.string.register_error_5_toast));
                            return;
                        }
                        manager.forgetPwd(ForgetActivity.this, mobile, code, password);
                    }
                    break;
                case R.id.authCode_tv:
                    if (authMobile(mobile)) {
                        /** 每次获取验证码，清除错误累计 */
                        count = 0;
                        v.setEnabled(false);
                        authCodeTV.setBackgroundResource(R.drawable.get_code_unpress);
                        timer.start();
                        manager.getAuthCode(ForgetActivity.this, mobile);
                    }

                    break;
                default:
                    break;
            }
        }
    };


    private boolean authPsd(String password, String authCode) {
        boolean ret = false;
        if (TextUtils.isEmpty(password)) {
            toastString(getResources().getString(R.string.login_error_3));
            return ret;
        } else if (password.length() < 6) {
            toastString(getResources().getString(R.string.register_error_2));
            return ret;
        }

//		if(TextUtils.isEmpty(authPassword)){
//			toastString(getResources().getString(R.string.register_error_3));
//			return ret;
//		}else if (!authPassword.equals(password)) {
//			toastString(getResources().getString(R.string.register_error_4));
//			return ret;
//		}
        if (TextUtils.isEmpty(authCode)) {
            toastString(getResources().getString(R.string.register_error_5));
            return ret;
        }

        return true;
    }

    private boolean authMobile(String mobile) {
        boolean ret = false;
        if (null == mobile) {
            toastString(getResources().getString(R.string.register_error_1));
            return ret;
        } else {
            boolean ismobile = mobile.matches("^(13|15|18|14|17)\\d{9}$");
            if (ismobile) {
                ret = true;
            } else {
                toastString(getResources().getString(R.string.login_error_1));
            }
            return ret;
        }
    }

    private void toastString(String message) {
        Notification.toast(this, message);
    }

    @Override
    public void onFailure(int errorCode, String errorMsg) {
//		ErrorMsgHandler.getInstance().onErrorMsg(this, errorCode, errorMsg);
        count++;
    }

    @Override
    public void onSuccess() {
        toastString(getResources().getString(R.string.modify_success));
        finish();
    }

    @Override
    public void onAuthCodeFailure(int errorCode, String errorMsg) {
        toastString(errorMsg);
        timer.cancel();
        authCodeTV.setEnabled(true);
        authCodeTV.setText(getResources().getString(R.string.register_get_auth_password));
    }

    @Override
    public void onAuthCodeSuccess(Object objdata) {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeAuthListener(this);
            manager.removeListener(this);
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
